<script setup>
import { ref, onMounted, computed, watch } from 'vue'
import { GoEnd, GoStart, Pause, PlayOne, Music } from '@icon-park/vue-next'
import '@/assets/common/common.scss'
import { getCoverService, getMusicService } from '@/api/download.js'

const emit = defineEmits(['next', 'pre'])
const handleNext = () => {
  emit('next')
}
const handlePer = () => {
  emit('pre')
}

const props = defineProps({
  music: {
    type: Object,
    required: true
  }
})

const audioPlayer = ref(null)
const currentTime = ref(0) // 当前播放时间
const duration = ref(0) // 音频总时长
const isPlaying = ref(false) // 是否正在播放
let isSliding = false // 标记是否正在拖动进度条

// 当音频准备好时更新总时长
const onLoadedMetadata = () => {
  if (audioPlayer.value) {
    duration.value = audioPlayer.value.duration || 0
    currentTime.value = 0 // 确保初始时间为 0
  }
}

// 更新进度条
const onTimeUpdate = () => {
  if (!isSliding && audioPlayer.value) {
    currentTime.value = audioPlayer.value.currentTime || 0
  }
}
// 监听歌曲播放结束
const onAudioEnded = () => {
  emit('next')
}
// 播放或暂停音频
const togglePlay = () => {
  if (audioPlayer.value) {
    if (isPlaying.value) {
      audioPlayer.value.pause()
    } else {
      audioPlayer.value.play().catch((err) => {
        console.error('播放失败:', err)
      })
    }
    isPlaying.value = !isPlaying.value
  }
}

// 拖动进度条
const onSliderStart = () => {
  isSliding = true // 开始拖动
}

const onSliderChange = (value) => {
  if (audioPlayer.value) {
    audioPlayer.value.currentTime = value // 更新音频播放时间
    currentTime.value = value // 同步滑块的值
  }
}

const onSliderEnd = () => {
  isSliding = false // 拖动结束
}

// 格式化时间为 mm:ss
const formatTime = (seconds) => {
  const minutes = Math.floor(seconds / 60)
  const secs = Math.floor(seconds % 60).toString().padStart(2, '0')
  return `${minutes}:${secs}`
}

// 计算属性：格式化当前时间和总时长
const formattedCurrentTime = computed(() => formatTime(currentTime.value))
const formattedDuration = computed(() => formatTime(duration.value))

// 监听 music prop 的变化，切换音频并自动播
watch(() => props.music.time, () => {
  if (props.music.index >= 0) {
    isPlaying.value = true
    audioPlayer.value.play()
  } else {
    isPlaying.value = false
    audioPlayer.value.pause()
  }
})

onMounted(() => {
  if (audioPlayer.value) {
    audioPlayer.value.addEventListener('loadedmetadata', onLoadedMetadata)
    audioPlayer.value.addEventListener('timeupdate', onTimeUpdate)
    audioPlayer.value.addEventListener('ended', onAudioEnded)
    audioPlayer.value.load() // 加载音频
  }
})


</script>

<template>
  <div class="music-player">
    <audio ref="audioPlayer"
           :autoplay="isPlaying"
           id="audioPlayer"
           :src="getMusicService(props.music.id)"
           style="display: none;">
    </audio>
  </div>
  <van-row>
    <van-col span="1" class="icon-center">
      <el-button circle class="play-button" @click="handlePer">
        <go-start theme="outline" size="25" :strokeWidth="5" />
      </el-button>
    </van-col>
    <van-col span="2" class="icon-center">
      <el-button circle @click="togglePlay" class="play-button-t">
        <template v-if="isPlaying">
          <pause theme="outline" size="45" :strokeWidth="4" />
        </template>
        <template v-else>
          <play-one theme="outline" size="45" :strokeWidth="4" />
        </template>
      </el-button>
    </van-col>
    <van-col span="1" class="icon-center">
      <el-button circle class="play-button" @click="handleNext">
        <go-end theme="outline" size="25" :strokeWidth="5" />
      </el-button>
    </van-col>
    <van-col span="3">
      <van-image
        width="70px"
        height="70px"
        :src="getCoverService(props.music.id)"
      >
        <template v-slot:error>
          <music theme="outline" size="20" fill="#333" :strokeWidth="3" />
        </template>
      </van-image>
    </van-col>
    <van-col span="13" class="vertical-layout">
      <p
        style="width:100%;
         margin:0;
         font-size: 15px;
         text-align: left">
        {{ props.music.name }} -- {{ props.music.artist }}
      </p>
      <el-slider
        v-model="currentTime"
        :max="duration"
        :format-tooltip="formatTime"
        @input="onSliderStart"
        @change="onSliderChange"
        @mouseup="onSliderEnd"
      />
    </van-col>
    <van-col span="3">
      <div class="time-info icon-center">
        <span>{{ formattedCurrentTime }}</span>
        &nbsp;/&nbsp;
        <span>{{ formattedDuration }}</span>
      </div>
    </van-col>
  </van-row>
</template>

<style scoped>

.van-row {
  width: 90%;
  height: 70px;
  margin: 0 auto;

  .vertical-layout {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
  }

  div {
    display: flex !important;
    align-items: center !important;
    justify-content: center;

    .play-button {
      width: 40px;
      height: 40px;
    }

    .play-button-t {
      width: 60px;
      height: 60px;
    }

  }
}

</style>
